package ru.susu.algebra.jtex.utils;

import java.math.BigInteger;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;

import ru.susu.algebra.field.quadratic.QuadraticInteger;
import ru.susu.algebra.jtex.ITexElement;
import ru.susu.algebra.jtex.formula.FormulaTexElement;
import ru.susu.algebra.jtex.formula.GreekSymbols;
import ru.susu.algebra.jtex.formula.MathSymbols;
import ru.susu.algebra.pair.Pair;
import ru.susu.algebra.util.NumberUtilities;
import ru.susu.algebra.util.StringUtilities;

/**
 * @author akargapolov
 * @since: 16.08.2010
 */
public class TexUtils
{
	public static String processElements(List<ITexElement> elements)
	{
		Collection<String> strings = Collections2.transform(elements, getElement2ContentFunction());
		return StringUtils.join(strings, StringUtilities.EMPTY_STRING);
	}

	public static Function<ITexElement, String> getElement2ContentFunction()
	{
		return new Function<ITexElement, String>()
		{
			@Override
			public String apply(ITexElement generator)
			{
				return generator == null ? null : generator.generateContent();
			}
		};
	}

	public static String getFactorization(BigInteger number)
	{
		StringBuffer buffer = new StringBuffer();
		for (Pair<Integer, Integer> pair : NumberUtilities.factorization(number))
		{
			if (buffer.length() > 0)
				buffer.append(FormulaTexElement.CDOT);
			buffer.append(pair.getKey());
			if (pair.getValue() > 1)
			{
				buffer.append("^{" + pair.getValue() + "}");
			}
		}
		return buffer.toString();
	}

	public static String index(Object index)
	{
		return "_{" + index + "}";
	}

	public static String pow(Object pow)
	{
		return "^{" + pow + "}";
	}

	public static String toTexString(QuadraticInteger value)
	{
		StringBuilder res = new StringBuilder();
		boolean aZero = BigInteger.ZERO.equals(value.getA());
		if (!aZero)
			res.append(value.getA());
		if (!value.getD().equals(BigInteger.ZERO) && !value.getB().equals(BigInteger.ZERO))
		{
			if (value.getB().compareTo(BigInteger.ZERO) >= 0)
			{
				if (!aZero)
					res.append(" + ");
			}
			else
				res.append(" - ");

			if (!value.getB().abs().equals(BigInteger.ONE))
				res.append(value.getB().abs());
			res.append(GreekSymbols.OMEGA + index(value.getD()));
		}
		else if (aZero)
			res.append(value.getA());
		return res.toString();
	}

	public static String inFigureBrackets(String text)
	{
		return "{" + text + "}";
	}

	public static String inBrackets(String text)
	{
		return MathSymbols.LEFT + MathSymbols.LEFT_BRACKET + text + MathSymbols.RIGHT + MathSymbols.RIGHT_BRACKET;
	}

}
